package com.eiisan.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.eiisan.core.util.api.Result;
import com.eiisan.web.feign.PayMentTransacClientApi;
import com.eiisan.web.feign.PaymentChannelClientApi;
import com.eiisan.web.model.dto.PayMentTransacDTO;
import com.eiisan.web.model.dto.PaymentChannelDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/**
 * 支付网站
 */
@Controller
public class PayController{
	@Autowired
	private PayMentTransacClientApi payMentTransacClientApi;
	@Autowired
	private PaymentChannelClientApi paymentChannelClientApi;

	@RequestMapping("/pay")
	public String pay(String payToken, Model model) {
		// 1.验证payToken参数
		if (StringUtils.isEmpty(payToken)) {
			model.addAttribute("error", "支付令牌不能为空!");
			return "500";
		}
		// 2.使用payToken查询支付信息
		Result<PayMentTransacDTO> tokenByPayMentTransac = payMentTransacClientApi.tokenByPayMentTransac(payToken);

		if (Result.isNotSuccess(tokenByPayMentTransac)) {
			model.addAttribute("error", tokenByPayMentTransac.getMessage());
			return "500";
		}
		// 3.查询支付信息
		PayMentTransacDTO data = tokenByPayMentTransac.getData();
		model.addAttribute("data", data);
		// 4.查询渠道信息
		List<PaymentChannelDTO> paymentChanneList = paymentChannelClientApi.selectAll();
		model.addAttribute("paymentChanneList", paymentChanneList);
		model.addAttribute("payToken", payToken);
		return "index";
	}


	@RequestMapping("/payHtml")
	public void payHtml(String channelId, String payToken, HttpServletResponse response) throws IOException {
		response.setContentType("text/html; charset=utf-8");
		Result<JSONObject> payHtmlData = payMentTransacClientApi.toPayHtml(channelId, payToken);
		if (Result.isSuccess(payHtmlData)) {
			JSONObject data = payHtmlData.getData();
			String payHtml = data.getString("payHtml");
			response.getWriter().print(payHtml);
		}
	}

}
